<?php

namespace app\admin\controller\order;

use app\common\controller\Backend;

/**
 * 服务订单管理
 *
 * @icon fa fa-circle-o
 */
class OrderService extends Backend
{

    /**
     * OrderService模型对象
     * @var \app\admin\model\order\OrderService
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\OrderService;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['service','user','member'])  // 增加member关联
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','order_no','amount','status','pay_time','complete_time','createtime']);
                $row->visible(['service']);
                $row->getRelation('service')->visible(['name']);
                $row->visible(['user']);
                $row->getRelation('user')->visible(['nickname','realname','mobile']);
                $row->visible(['member']);
                $row->getRelation('member')->visible(['nickname','realname','mobile','avatar']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function refund($ids = null)
    {
        $row = $this->model->get($ids);
        
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post();
            
            try {
                $result = null;
                $out_request_no = $row->out_request_no;
                if(!$out_request_no){
                    $out_request_no = date('YmdHis') . rand(1000, 9999);
                }
                if ($row->pay_type == 'alipay') {
                    $result = \app\common\library\Refund::alipay($row->order_no, $params['refund_amount'], $params['reason'],$out_request_no);
                } else if ($row->pay_type == 'wechat') {
                    $result = \app\common\library\Refund::wechat($row->order_no, $row->amount, $params['refund_amount'], $params['reason'],$out_request_no);
                }else{
                    $this->error('不支持代金券退款');

                }
                // 记录退款日志
                // \think\Db::name('refund_log')->insert([
                //     'order_id' => $row->id,
                //     'type' => $row->pay_type,
                //     'amount' => $params['refund_amount'],
                //     'reason' => $params['reason'],
                //     'createtime' => time()
                // ]);
                if ($result && $result['status']) {
                    // 更新订单状态为已退款
                    $row->status = 5; // 已退款
                    $row->refund_time = time();
                    $row->refund_amount = $params['refund_amount'];
                    $row->refund_reason = $params['reason'];
                    $row->out_request_no = $out_request_no;
                    $row->save();
                    // 记录用户消费记录
                    \think\Db::name('user_consume_log')->insert([
                        'user_id' => $row->user_id,
                        'type' => 'refund',
                        'target_id' => $row->id,
                        'target_title' => '订单退款',
                        'amount' => $params['refund_amount'],
                        'createtime' => time()
                    ]);
                    $this->success('退款成功');
                }else{
                    $this->error('退款失败'.$result['message']);
                }
            } catch (\think\exception\PDOException $e) {
                $this->error($e->getMessage());
            }
        }
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
